package ch.fhnw.edu.rental.daos.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import ch.fhnw.edu.rental.daos.RentalDAO;
import ch.fhnw.edu.rental.daos.UserDAO;
import ch.fhnw.edu.rental.model.Movie;
import ch.fhnw.edu.rental.model.User;

public class JdbcUserDAO extends SimpleJdbcDaoSupport implements UserDAO {

	private RentalDAO rentalDAO;

	public void setRentalDAO(RentalDAO rentalDAO) {
		this.rentalDAO = rentalDAO;
	}

	@Override
	public User getById(Long id) {
		SimpleJdbcTemplate template = getSimpleJdbcTemplate();
		Map<String, Object> res = template.queryForMap("select * from USERS where USER_ID = ?", new Object[]{id});
		
		User u = new User((String)res.get("USER_NAME"),
						  (String)res.get("USER_FIRSTNAME"));
		u.setId((Long)res.get("USER_ID"));
		u.setRentals(rentalDAO.getRentalsByUser(u));
		u.setEmail((String)res.get("USER_EMAIL"));
		return u;
	}

	@Override
	public List<User> getAll() {
		SimpleJdbcTemplate template = getSimpleJdbcTemplate();
		return template.query("select * from USERS",
							  new RowMapper<User>(){
							  	public User mapRow(ResultSet rs, int row) throws SQLException {
									return createUser(rs);
							  	}
							  }
							  );
	}

	@Override
	public List<User> getByName(String name) {
		SimpleJdbcTemplate template = getSimpleJdbcTemplate();
		return template.query("select * from USERS where USER_NAME = ?",
							  new RowMapper<User>(){
							  	public User mapRow(ResultSet rs, int row) throws SQLException {
									return createUser(rs);
							  	}
							  },
							  name
							  );
	}

	@Override
	public void saveOrUpdate(User user) {
		// TODO Auto-generated method stub
	}

	@Override
	public void delete(User user) {
		// TODO Auto-generated method stub
	}
	
	private User createUser(ResultSet rs) throws SQLException{
		User u = new User(rs.getString("USER_NAME"), rs.getString("USER_FIRSTNAME"));
		u.setId(rs.getLong("USER_ID"));
		u.setRentals(rentalDAO.getRentalsByUser(u));
		u.setEmail(rs.getString("USER_EMAIL"));
		return u;
	}

}
